/**
 * Created by Adi(adi@imeth.cn) on 2018/9/3.
 */

import React, { Fragment } from 'react';
import Page from 'src/routes/Page';
import { autobind } from 'core-decorators';
import StandardTable from 'src/components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import QueryData from 'src/components/queryData/QueryData';
import OperateModelView from 'src/components/operateModelView/OperateModelView';
import Selector from 'src/components/selector/Selector';
import BasicModelView from 'src/components/basicModelView/BasicModelView';
import { Card, Button, Input, Switch } from 'antd';
import { connect } from 'dva/index';

@connect(({ PayChannel, loading }) => ({
  PayChannel,
  loading: loading.models.PayChannel,
}))
@autobind
class PayChannel extends Page {
  constructor(props) {
    super(props);
    this.state = {
      results: [],
      paging: {},
      selectedRows: [],
      addShow: false,
      updateShow: false,
      stateShow: false,
      shrink: true,
      formValues: {},
      queryFromValue: null,
    };
    this.stateList = [
      { value: 'STATE_OPEN', label: '激活' },
      { value: 'STATE_CLOSE', label: '冻结' },
    ];
    this.stateObject = {
      STATE_OPEN: true,
      STATE_CLOSE: false,
    };
  }

  componentDidMount() {
    this.dispatch({
      type: 'PayChannel/payChannelList',
    });
  }

  shouldComponentUpdate(props, state) {
    let { PayChannel } = props;

    let {
      getByIdResult,
      saveResult,
      updateResult,
      freezeResult,
      activateResult,
      payChannelListResult,
    } = PayChannel;

    this.rollout(
      payChannelListResult,
      false,
      (result, mes, paging) => {
        this.state.results = result;
        this.state.paging = paging;
      },
      false
    );

    this.rollout(
      getByIdResult,
      false,
      result => {
        this.state.formValues = result;
        this.state.updateShow = true;
      },
      false
    );

    this.rollout(
      saveResult,
      false,
      result => {
        this.state.addShow = false;
        this.dispatch({
          type: 'PayChannel/payChannelList',
        });
      },
      false
    );

    this.rollout(
      updateResult,
      false,
      result => {
        this.state.updateShow = false;
        this.dispatch({
          type: 'PayChannel/payChannelList',
        });
      },
      false
    );

    this.rollout(
      freezeResult,
      false,
      result => {
        this.state.stateShow = false;
        this.dispatch({
          type: 'PayChannel/payChannelList',
        });
      },
      false
    );

    this.rollout(
      activateResult,
      false,
      result => {
        this.state.stateShow = false;
        this.dispatch({
          type: 'PayChannel/payChannelList',
        });
      },
      false
    );

    return this.equal(props, state);
  }

  render() {
    const {
      selectedRows,
      addShow,
      shrink,
      updateShow,
      formValues,
      stateShow,
      results,
      paging,
    } = this.state;

    // table 显示列表
    const columns = [
      {
        title: '名称', // 列表显示
        dataIndex: 'name', // 数据展示对应字段
      },
      {
        title: '费率',
        dataIndex: 'rate',
      },
      {
        title: '手续费',
        dataIndex: 'fee',
      },
      {
        title: '最大限额',
        dataIndex: 'limitMax',
      },
      {
        title: '状态',
        dataIndex: 'state',
        // 可对单项内容重新渲染 text 为当前行的值 record 为当前行数据 index 为当前行索引
        render: (text, record, index) => (
          <Switch
            checkedChildren="激活"
            unCheckedChildren="冻结"
            checked={this.stateObject[record.state]}
            onChange={() => this.showStateView(text, record, index)}
          />
        ),
      },
      {
        title: '操作',
        render: (text, record, index) => (
          <Fragment>
            <Button type="primary" onClick={() => this.showUpdateView(text, record, index)}>
              修改
            </Button>
          </Fragment>
        ),
      },
    ];

    // 渲染按钮内容
    const button = (
      <span>
        <Button type="primary" style={{ marginRight: '10px' }} onClick={this.showAddView}>
          新增
        </Button>
      </span>
    );

    // 查询显示列表
    const searchList = [
      {
        value: 'name', // 查询对应的数据字段名
        renderItem: <Input placeholder="请输入名称" />, // 对应的渲染内容
      },
      {
        value: 'state',
        renderItem: <Selector placeholder="请选择状态" selectList={this.stateList} />,
      },
    ];

    const formList = [
      {
        label: '名称',
        value: 'name',
        rules: [
          {
            required: true,
            message: '名称不能为空',
          },
        ],
        initialValue: formValues && formValues.name, // 设置初始值 (修改时传入的数据)
        renderItem: <Input placeholder="请输入名称" />,
      },
      {
        label: '代号',
        value: 'code',
        rules: [],
        initialValue: formValues && formValues.code,
        renderItem: <Input placeholder="请输入代号" />,
      },
      {
        label: '费率',
        value: 'rate',
        rules: [],
        initialValue: formValues && formValues.rate,
        renderItem: <Input placeholder="请输入输入费率" />,
      },
      {
        label: '手续费(分)',
        value: 'fee',
        initialValue: formValues && formValues.fee,
        renderItem: <Input placeholder="请输入手续费" />,
      },
      {
        label: '状态',
        value: 'state',
        initialValue: formValues && formValues.state,
        renderItem: (
          <Selector
            placeholder="请选择状态"
            selectList={this.stateList}
            defaultValue={formValues.state}
          />
        ),
      },
      {
        label: '适配器',
        value: 'adapter',
        initialValue: formValues && formValues.adapter,
        renderItem: <Input placeholder="请输入适配器" />,
      },
      {
        label: '开始时间',
        value: 'startTime',
        initialValue: formValues && formValues.startTime,
        renderItem: <Input placeholder="请输入开始时间" />,
      },
      {
        label: '结束时间',
        value: 'endTime',
        initialValue: formValues && formValues.endTime,
        renderItem: <Input placeholder="请输入结束时间" />,
      },
      {
        label: '最低手续费(分)',
        value: 'limitMinFee',
        initialValue: formValues && formValues.limitMinFee,
        renderItem: <Input placeholder="请输入最低手续费" />,
      },
      {
        label: '最低限额',
        value: 'limitMin',
        initialValue: formValues && formValues.limitMin,
        renderItem: <Input placeholder="请输入最低限额" />,
      },
      {
        label: '最大限额',
        value: 'limitMax',
        initialValue: formValues && formValues.limitMax,
        renderItem: <Input placeholder="请输入最大限额" />,
      },
    ];

    return (
      <PageHeaderLayout title="支付通道管理">
        <Card bordered={false}>
          {/*渲染查询内容*/}
          <QueryData
            shrink={shrink}
            queryList={searchList}
            operateExtra={button}
            onQuery={this.onQuery}
          />
          {/*渲染列表内容*/}
          <StandardTable
            pagination={paging}
            selectedRows={selectedRows}
            loading={this.props.loading}
            columns={columns}
            data={results}
            onSelectRow={this._onSelectRow}
            onChange={this._onChange}
          />
        </Card>
        {addShow && (
          <OperateModelView
            visible={addShow}
            title="新增支付通道信息"
            onCancel={() => this.setState({ addShow: false })}
            formItemList={formList}
            onSubmit={this.save}
          />
        )}
        {updateShow && (
          <OperateModelView
            visible={updateShow}
            title="修改支付通道信息"
            onCancel={() => this.setState({ updateShow: false })}
            formItemList={formList}
            formData={formValues}
            onSubmit={this.update}
          />
        )}
        {stateShow && (
          <BasicModelView
            visible={stateShow}
            title="确认操作"
            extra={<div>确认？</div>}
            onCancel={() => this.setState({ stateShow: false })}
            onOk={this.changeState}
          />
        )}
      </PageHeaderLayout>
    );
  }

  // 行选择
  _onSelectRow(row) {
    this.setState({
      selectedRows: row,
    });
  }

  // 分页 过滤 排序
  _onChange(page, filter, sort) {
    const { queryFromValue } = this.state;
    this.state.selectedRows = [];
    this.dispatch({
      type: 'PayChannel/payChannelList',
      payload: {
        ...queryFromValue,
        current: page.current,
        size: page.pageSize,
      },
    });
  }

  // 显示新增弹窗
  showAddView() {
    this.setState({ formValues: {}, addShow: true });
  }

  // 显示修改弹窗
  // text 为当前行的值
  // record 为当前行数据
  // index 为当前行索引
  showUpdateView(text, record, index) {
    //  获取详情
    this.dispatch({
      type: 'PayChannel/getById',
      payload: record.id,
    });
  }

  showStateView(text, record, index) {
    this.setState({ stateShow: true, formValues: record });
  }

  // 开关操作
  changeState() {
    let { formValues } = this.state;
    if (this.stateObject[formValues.state]) {
      // 冻结
      this.dispatch({
        type: 'PayChannel/freeze',
        payload: {
          id: formValues.id,
        },
      });
    } else {
      // 激活
      this.dispatch({
        type: 'PayChannel/activate',
        payload: {
          id: formValues.id,
        },
      });
    }
  }

  // 保存
  // formValues 为表单数据
  save(formValues) {
    this.dispatch({
      type: 'PayChannel/save',
      payload: {
        ...formValues,
      },
    });
  }

  // 修改
  update(formValues) {
    this.dispatch({
      type: 'PayChannel/update',
      payload: {
        ...formValues,
      },
    });
  }

  //  查询方法
  onQuery(formValues) {
    this.setState({ queryFromValue: formValues });
    this.dispatch({
      type: 'PayChannel/payChannelList',
      payload: {
        ...formValues,
      },
    });
  }
}

export default PayChannel;
